import { useState, useEffect } from 'react';
import { Card, Typography, Input, Select, Button, App } from 'antd';
import { getUrlPara, getItemIdFromAliurl } from '../../utils/common';
import { getBindAll, submitCopyTask, type ShopData } from '../../services/login';

type ShopOption = { label: string; value: string };
type ItemParsed = { url: string; itemId: string; platform: string };

export default function CopyItem() {
  const { message } = App.useApp();
  const [copyItemUrls, setCopyItemUrls] = useState<string>('');
  const [shopId, setShopId] = useState<string>('');
  const [shopOptions, setShopOptions] = useState<ShopOption[]>([]);
  const [loading, setLoading] = useState<boolean>(false);
  const [submitting, setSubmitting] = useState<boolean>(false);

  // 获取店铺列表
  useEffect(() => {
    const fetchShopList = async () => {
      try {
        setLoading(true);
        const response = await getBindAll();
        console.log('getBindAll 响应:', response);
        const { data, code } = response.result.body;
        if (code === 200 && Array.isArray(data)) {
          const options = data.map((shop: ShopData) => ({
            label: `${shop.shopName} (${shop.platform})`,
            value: shop.shopId
          }));
          setShopOptions(options);
        } else {
          message.error('获取店铺列表失败');
        }
      } catch (error) {
        console.error('获取店铺列表失败:', error);
        message.error('获取店铺列表失败');
      } finally {
        setLoading(false);
      }
    };

    fetchShopList();
  }, [message]);

  const normalizeUrls = () => {
    if (!copyItemUrls) return;
    const lines = copyItemUrls.split('\n');
    if (copyItemUrls.indexOf('1688.com') === -1) {
      message.error('应平台管控,仅支持1688货源!');
      return;
    }
    const slice = lines.length > 500 ? lines.slice(0, 500) : [...lines];
    const parsed: ItemParsed[] = [];
    const resultUrls: string[] = [];
    slice.forEach((raw) => {
      if (!raw) return;
      const a = raw.replace(/\s+/g, '');
      if (!a) return;
      const obj: ItemParsed = { url: '', itemId: '', platform: '' };
      if (a.indexOf('mobile.yangkeduo.com') !== -1 || a.indexOf('mobile.pinduoduo.com') !== -1) {
        const p = getUrlPara(a);
        obj.url = `https://mobile.yangkeduo.com/goods.html?goods_id=${p.goods_id}`;
        obj.itemId = String(p.goods_id || '');
        obj.platform = 'pdd';
      } else if (a.indexOf('item.taobao.com') !== -1) {
        const p = getUrlPara(a);
        obj.url = `https://item.taobao.com/item.htm?id=${p.id}`;
        obj.itemId = String(p.id || '');
        obj.platform = 'taobao';
      } else if (a.indexOf('tmall.com') !== -1) {
        const p = getUrlPara(a);
        obj.url = `https://detail.tmall.com/item.htm?id=${p.id}`;
        obj.itemId = String(p.id || '');
        obj.platform = 'taobao';
      } else if (a.indexOf('1688.com') !== -1) {
        const id = getItemIdFromAliurl(a);
        obj.url = `https://detail.1688.com/offer/${id}.html`;
        obj.itemId = id;
        obj.platform = '1688';
      } else if (a.indexOf('kwaixiaodian.com') !== -1) {
        const p = getUrlPara(a);
        obj.url = `https://app.kwaixiaodian.com/page/kwaishop-goods-detail-h5-vue/detail?id=${p.id}`;
        obj.itemId = String(p.id || '');
        obj.platform = 'kuaishou';
      }
      if (obj.url) {
        resultUrls.push(obj.url);
        parsed.push(obj);
      }
    });
    const uniqUrls = Array.from(new Set(resultUrls));
    setCopyItemUrls(uniqUrls.join('\n'));
    // parsed 去重按 url
    // 如需后续提交使用可存 state
  };

  const handleSubmit = async () => {
    if (!shopId) {
      message.warning('请选择店铺!');
      return;
    }
    if (!copyItemUrls) {
      message.warning('请填写商品链接!');
      return;
    }

    try {
      setSubmitting(true);

      // 按回车键分割URL为数组
      const urls = copyItemUrls
        .split('\n')
        .map(url => url.trim())
        .filter(url => url.length > 0);

      if (urls.length === 0) {
        message.warning('请输入有效的商品链接!');
        return;
      }

      // 提交任务到选中的店铺
      const { result } = await submitCopyTask({ shopId, urls });
      console.log("🚀 ~ handleSubmit ~ result:", result.body)

      // 检查请求是否成功
      if (result?.body?.code === 200) {
        message.success(`已成功提交铺货任务，共 ${urls.length} 个商品`);
        setCopyItemUrls('');
        setShopId('');
      } else {
        message.error('提交铺货任务失败，请重试');
      }
    } catch (error) {
      console.error('提交铺货任务失败:', error);
      message.error('提交铺货任务失败，请重试');
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <Card title={<>
      <Typography.Text strong style={{ fontSize: 18 }}>商品复制</Typography.Text>
      <Typography.Text type="secondary" style={{ marginLeft: 8 }}>
        （仅支持1688商品，示例:https://detail.1688.com/offer/651234566292.html）
      </Typography.Text>
    </>}>
      <Input.TextArea
        value={copyItemUrls}
        onChange={(e) => setCopyItemUrls(e.target.value)}
        rows={12}
        placeholder="请输入商品链接，多个链接每行一个"
        onInput={normalizeUrls}
      />
      <div style={{ marginTop: 16 }}>
        <div style={{ fontWeight: 600, marginBottom: 8 }}>请选择要添加的店铺</div>
        <Select
          style={{ width: '100%' }}
          placeholder="请选择店铺"
          value={shopId}
          onChange={setShopId}
          options={shopOptions}
          loading={loading}
          disabled={loading}
        />
      </div>
      <div style={{ marginTop: 16, textAlign: 'center' }}>
        <Button
          type="primary"
          size="large"
          onClick={handleSubmit}
          loading={submitting}
          disabled={submitting}
        >
          {submitting ? '提交中...' : '一 键 铺 货'}
        </Button>
      </div>
    </Card>
  );
}


